<template>
  <div>
    <h2 style="text-align: center">发布新课程</h2>
    <el-steps align-center :active="1" process-status="wait" style="margin-bottom: 40px;">
      <el-step title="填写课程基本信息"></el-step>
      <el-step title="创建课程大纲"></el-step>
      <el-step title="提交审核"></el-step>
    </el-steps>
    <!--表单-->
    <el-form label-width="120px" ref="course">
      <!-- 课程标题 -->
      <el-form-item label="课程标题">
        <el-input type="text" v-model="courseInfo.title" placeholder="课程标题"/>
      </el-form-item>


      <!-- 课程简介-->
      <el-form-item label="课程简介">
        <Tinymce :height="300" v-model="courseInfo.description"/>
      </el-form-item>
      <!-- 课程封面-->
      <el-form-item label="课程封面">
        <el-upload
          class="avatar-uploader"
          :action="OSS_API + '/oss/uploadImg?dir=cover'"
          :show-file-list="false"
          :on-success="coverUploadSuccess"
          :before-upload="beforeCoverUpload">
          <img v-if="courseInfo.cover" :src="courseInfo.cover" class="avatar"/>
          <i v-else class="el-icon-plus avatar-uploader-icon"/>
        </el-upload>
      </el-form-item>
      <!-- 所属分类 -->
      <el-form-item label="科目分类">
        <template>
          <!--一级科目-->
          <el-select placeholder="请选择一级科目" @change="subjectChange" v-model="courseInfo.subjectParentId">
            <el-option
              v-for="item in subjectOneList"
              :key="item.id"
              :label="item.label"
              :value="item.id">
            </el-option>
          </el-select>
          <!--二级科目-->
          <el-select placeholder="请选择二级科目" ref="select" v-model="courseInfo.subjectId">
            <el-option
              v-for="item in subjectTwoList"
              :key="item.id"
              :label="item.label"
              :value="item.id">
            </el-option>
          </el-select>
        </template>
      </el-form-item>
      <!-- 课程讲师 -->
      <el-form-item label="课程讲师">
        <el-select v-model="courseInfo.teacherId" filterable placeholder="请选择">
          <el-option
            v-for="teacher in teachers"
            :key="teacher.id"
            :label="teacher.name"
            :value="teacher.id">
          </el-option>
        </el-select>
      </el-form-item>
      <!-- 总课时 -->
      <el-form-item label="总课时">
        <el-input-number :min="1" v-model="courseInfo.lessonNum" controls-position="right"/>
      </el-form-item>
      <!-- 课程价格 -->
      <el-form-item label="课程价格">
        <el-input-number :min="0" v-model="courseInfo.price" controls-position="right"/>
        元
      </el-form-item>
      <el-form-item>
        <el-button @click="save" type="primary">保存并下一步</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>

import {createCourse, updateCourse, findByIdCourse} from '@/api/course/course'
import {findAllTeacher} from '@/api/teacher/teacher'
import {findAllSubject, findOneByTwo} from '../../api/subject/subject'
// 文本编辑器
import Tinymce from '../../components/Tinymce'

export default {
  components: {Tinymce},
  name: "save",
  data() {
    return {
      // 课程
      courseInfo: {
        id: null,
        title: '',
        lessonNum: 0,
        price: 0,
        description: '',
        // 二级
        teacherId: null,
        subjectId: null,
        cover: '',
        // 一级
        subjectParentId: null,
      },
      // id
      id: null,
      // 讲师
      teachers: [],
      // 一级科目
      subjectOneList: null,
      // 二级科目
      subjectTwoList: null,
      // 地址
      OSS_API: 'http://localhost:9999',
    }
  },
  created() {
    // 查询所有讲师
    this.findAllTeacher()
    // 查询所有科目
    this.findSubject()
    // 判断创建课程还是修改课程
    setTimeout(() => {
      this.ifCourse()
    }, 200)


  },
  methods: {
    // 查询所有的科目
    async findSubject() {
      let result = await findAllSubject()
      if (result.code !== 20000) {
        this.$message.error("加载科目失败，请稍后重试")
        return false
      }
      this.subjectOneList = result.data;

    },
    // 选择器，选择科目
    async subjectChange() {
      // 二级科目是否已经存在？存在则清空
      if (this.subjectTwoList) {
        this.courseInfo.subjectId = ''
      }

      // 根据一级科目id，获取二级科目的列表
      this.subjectOneList.forEach(sub => {
        if (sub.id === this.courseInfo.subjectParentId) {
          // 二级科目
          this.subjectTwoList = sub.children
        }
      })
    },
    // 提交请求
    async save() {
      if (this.id) {
        // 修改
        await this.updateCourse()
      } else {
        // 添加
        await this.saveCourse()
      }
    },
    // 创建课程
    async saveCourse() {
      // 发送请求创建课程
      let result = await createCourse(this.courseInfo)
      if (result.code === 20000) {
        // 路由跳转
        this.$router.push({path: '/course/info/' + result.data})
      } else {
        this.$message.error("保存失败")
      }
    },
    // 修改课程
    async updateCourse() {
      let result = await updateCourse(this.courseInfo)
      if (result.code === 20000) {
        // 路由跳转
        this.$router.push({path: '/course/info/' + result.data})
      } else {
        this.$message.error("保存失败")
      }
    },
    // 创建课程数据回显
    async echoCourse() {
      let result = await findByIdCourse(this.id)
      if (result.code !== 20000) {
        this.$message.error("数据加载异常，请稍后重试！")
        return false
      }
      // 回显数据
      this.courseInfo = result.data
      // 回显操作
      await this.subjectChange()
    },
    // 判断修改还是创建
    async ifCourse() {
      // 获取路由的参数
      if (this.$route.params && this.$route.params.id) {
        this.id = this.$route.params.id
        // 数据回显
        await this.echoCourse()
      } else {
        // 路由没有随带id
        this.id = null
      }
    },
    // 获取全部的讲师
    async findAllTeacher() {
      let result = await findAllTeacher()
      if (result.code !== 20000) {
        this.$message.error("获取讲师失败，请稍后重试！")
        return false;
      }
      this.teachers = result.data
    },
    // 上传课堂封面
    coverUploadSuccess(res, file) {
      if (res.code === 20000) {
        this.$message.success('上传成功！')
        this.courseInfo.cover = res.data
        return false
      }
      this.$message.error('上传失败,' + res.data);
    },
    // 上传封面之前
    beforeCoverUpload(file) {
      let testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
      const extension =
        testmsg === "jpg" ||
        testmsg === "JPG" ||
        testmsg === "png" ||
        testmsg === "PNG" ||
        testmsg === "bpm" ||
        testmsg === "BPM";
      const isLt50M = file.size / 1024 / 1024 < 10;
      if (!extension) {
        this.$message({
          message: "上传图片只能是jpg / png / bpm格式!",
          type: "error"
        });
        return false; //必须加上return false; 才能阻止
      }
      if (!isLt50M) {
        this.$message({
          message: "上传文件大小不能超过 10MB!",
          type: "error"
        });
        return false;
      }
      return extension || isLt50M;
    }

  },
  watch: {
    // 路由改变时判断id
    $route() {
      this.ifCourse()
    }
  },

}
</script>

<style scoped lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
